﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.ETL.Domain.Services
{
    public class QueryService
    {
        public SingleResult<Data.TaskSummary> Query4Task()
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                Data.TaskSummary summary = dbContext.Database.SqlQuery<Data.TaskSummary>("exec [ETL_SP_GetSummary4TaskCount]").SingleOrDefault();
                summary.Tasks = dbContext.Database.SqlQuery<Data.TaskSummary.TaskExecuteRecord>("exec [ETL_SP_GetSummary4TaskList]").ToList();

                return new SingleResult<Data.TaskSummary>(summary);
            }
        }

        public ListResult<Data.DtSerCountSummary> Query4DtSerCount()
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                List<Data.DtSerCountSummary> list = dbContext.Database.SqlQuery<Data.DtSerCountSummary>("exec [ETL_SP_GetSummary4DtSerCount]").ToList();

                return new ListResult<Data.DtSerCountSummary>(true, 0, "", list);
            }
        }

        public SingleResult<Data.DtTableSummary> Query4DtTable()
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                Data.DtTableSummary summary = dbContext.Database.SqlQuery<Data.DtTableSummary>("exec [ETL_SP_GetSummary4DtTableCount]").SingleOrDefault();

                summary.Tables = dbContext.Database.SqlQuery<Data.DtTableSummary.Table>("exec [ETL_SP_GetSummary4DtTableList]").ToList();
                for (int index = 0; index < summary.Tables.Count; index++)
                {
                    summary.Tables[index].Sources = StoredProcedureMapping.GetDataSourceListByDataTable(dbContext, summary.Tables[index].Id);
                }

                return new SingleResult<Data.DtTableSummary>(summary);
            }
        }

        public SingleResult<Data.ExtactSummary> Query4AppExtraction()
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                Data.ExtactSummary summary = new Data.ExtactSummary();

                summary.Items = dbContext.Database.SqlQuery<Data.ExtactSummary.Item>("exec [ETL_SP_GetSummary4AppExtraction]").ToList();

                return new SingleResult<Data.ExtactSummary>(summary);
            }
        }

        public SingleResult<Entities.Maintainer> GetMantainer(Guid id)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                Entities.Maintainer maintainer = dbContext.Set<Entities.Maintainer>().SingleOrDefault(p => p.Id == id);
                return new SingleResult<Entities.Maintainer>(maintainer);
            }
        }

        public ListResult<Entities.Maintainer> QueryMantainerList(string filter)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                if (string.IsNullOrEmpty(filter))
                {
                    List<Entities.Maintainer> list = dbContext.Set<Entities.Maintainer>().OrderBy(p => p.Name).ToList();
                    return new ListResult<Entities.Maintainer>(true, 0, string.Empty, list);
                }
                else
                {
                    List<Entities.Maintainer> list = dbContext.Set<Entities.Maintainer>()
                        .Where(p => p.Name.Contains(filter)
                            || p.Email.Contains(filter)
                            || p.Mobile.Contains(filter))
                        .OrderBy(p => p.Name).ToList();
                    return new ListResult<Entities.Maintainer>(true, 0, string.Empty, list);
                }
            }
        }
        public ListResult<Data.IntegrityCheckInstance> QueryIntegrityCheckInstanceList(Guid taskId)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                List<CPPEI.ETL.Domain.IntegrityCheck.ICFactory.ICInfo> icInfoList = IntegrityCheck.ICFactory.EnumIC();

                List<Entities.IntegrityCheckInstance> entityList = dbContext.Set<Entities.IntegrityCheckInstance>().Where(p => p.TaskId == taskId).OrderBy(p => p.CreatedTime).ToList();

                List<Data.IntegrityCheckInstance> list = new List<Data.IntegrityCheckInstance>();
                for (int index = 0; index < entityList.Count; index++)
                {
                    Data.IntegrityCheckInstance data = new Data.IntegrityCheckInstance();
                    Guid instanceId = entityList[index].Id;
                    List<Entities.IntegrityCheckParameter> parameterList = dbContext.Set<Entities.IntegrityCheckParameter>().Where(p => p.InstanceId == instanceId).OrderBy(p => p.SortIndex).ToList();
                    Dictionary<string, string> parameters = new Dictionary<string, string>();
                    foreach (var item in parameterList)
                    {
                        parameters.Add(item.Name, item.Value);
                    }

                    data.Entity = entityList[index];
                    foreach (var icInfo in icInfoList)
                    {
                        if (data.Entity.IntegrityCheckId == icInfo.Id)
                        {
                            data.IntegrityCheckName = icInfo.Name;
                            data.IntegrityCheckDescription = icInfo.Description;
                            data.ConditionText = CPPEI.ETL.Domain.IntegrityCheck.ICFactory.Create(icInfo.Id).GetConditionText(parameters);
                            break;
                        }
                    }
                    list.Add(data);
                }
                return new ListResult<Data.IntegrityCheckInstance>(true, 0, string.Empty, list);
            }
        }

        public SingleResult<Data.IntegrityCheckInstanceDetail> GetIntegrityCheckInstance(Guid id)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                List<CPPEI.ETL.Domain.IntegrityCheck.ICFactory.ICInfo> icInfoList = IntegrityCheck.ICFactory.EnumIC();

                Entities.IntegrityCheckInstance entity = dbContext.Set<Entities.IntegrityCheckInstance>().SingleOrDefault(p => p.Id == id);

                if (entity == null)
                {
                    return new SingleResult<Data.IntegrityCheckInstanceDetail>(false, ErrorCode.COM_OBJNotExist, ErrorCode.String(ErrorCode.COM_OBJNotExist), null);
                }

                List<Data.IntegrityCheckInstance> list = new List<Data.IntegrityCheckInstance>();

                Data.IntegrityCheckInstanceDetail data = new Data.IntegrityCheckInstanceDetail();
                data.Entity = entity;
                IntegrityCheck.ICFactory.ICInfo info = null;
                foreach (var icInfo in icInfoList)
                {
                    if (data.Entity.IntegrityCheckId == icInfo.Id)
                    {
                        info = icInfo;
                        data.IntegrityCheckName = icInfo.Name;
                        data.IntegrityCheckDescription = icInfo.Description;
                        break;
                    }
                }

                List<Entities.IntegrityCheckParameter> peList = dbContext.Set<Entities.IntegrityCheckParameter>().Where(p => p.InstanceId == id).OrderBy(p => p.SortIndex).ToList();

                data.ParameterList = new List<Data.IntegrityCheckParameter>();
                for (int index = 0; index < peList.Count; index++)
                {
                    Data.IntegrityCheckParameter parameter = new Data.IntegrityCheckParameter();
                    parameter.Entity = peList[index];
                    for (int icPIndex = 0; icPIndex < info.ParameterList.Count; icPIndex++)
                    {
                        if (string.Equals(parameter.Entity.Name, info.ParameterList[icPIndex].Name))
                        {
                            parameter.Caption = info.ParameterList[icPIndex].Caption;
                            parameter.Type = info.ParameterList[icPIndex].Type.FullName;
                            break;
                        }
                    }

                    data.ParameterList.Add(parameter);
                }

                return new SingleResult<Data.IntegrityCheckInstanceDetail>(data);
            }
        }

        public PagedList<Entities.ETaskExecLog> QueryTaskExecLog(string filter, DateTime? begin, DateTime? end, int? state, int start, int limit)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {


                List<Entities.ETaskExecLog> list = dbContext.Set<Entities.ETaskExecLog>().
                    Where(x => (string.IsNullOrEmpty(filter) || x.TaskName.Contains(filter))
                    && (!begin.HasValue || x.CreatedTime >= begin)
                    && (!end.HasValue || x.CreatedTime <= end)
                    && (!state.HasValue || x.Result == state)
                    ).OrderByDescending(p => p.CreatedTime)
                       .Skip(start)
                       .Take(limit).ToList();
                int total = dbContext.Set<Entities.ETaskExecLog>().Count(x => (string.IsNullOrEmpty(filter) || x.TaskName.Contains(filter))
                    && (!begin.HasValue || x.CreatedTime >= begin)
                    && (!end.HasValue || x.CreatedTime <= end) 
                    && (!state.HasValue || x.Result == state));
                return new PagedList<Entities.ETaskExecLog>(true, ErrorCode.COM_NoError, string.Empty, start, limit, total, list);
                //if (string.IsNullOrEmpty(filter))
                //{
                //    List<Entities.ETaskExecLog> list = dbContext.Set<Entities.ETaskExecLog>().OrderByDescending(p => p.CreatedTime)
                //        .Skip(start)
                //        .Take(limit).ToList();
                //    int total = dbContext.Set<Entities.ETaskExecLog>().Count();
                //    return new PagedList<Entities.ETaskExecLog>(true, ErrorCode.COM_NoError, string.Empty, start, limit, total, list);
                //}
                //else
                //{
                //    List<Entities.ETaskExecLog> list = dbContext.Set<Entities.ETaskExecLog>().Where(p => p.TaskName.Contains(filter))
                //        .OrderByDescending(p => p.CreatedTime)
                //        .Skip(start)
                //        .Take(limit).ToList();
                //    int total = dbContext.Set<Entities.ETaskExecLog>().Where(p => p.TaskName.Contains(filter)).Count();
                //    return new PagedList<Entities.ETaskExecLog>(true, ErrorCode.COM_NoError, string.Empty, start, limit, total, list);
                //}
            }
        }
    }
}
